package com.yyk.yykywd.ui.login

import android.os.CountDownTimer
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.lifecycle.*
import com.orhanobut.logger.Logger
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.AlidayuSendsmsInfo
import com.yyk.yykywd.bean.LoginLoginInfo
import com.yyk.yykywd.http.ApiService
import com.yyk.yykywd.network.BusinessApi
import com.yyk.yykywd.util.Md5Util2
import com.yyk.yykywd.util.ToastUtil
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch
import java.util.*

/**
 * 文件描述：
 * Created by guo on 2019-11-18.
 */
class LoginViewModel : ViewModel() {

    companion object {
        // Time when the game is over
        const val DONE = 0L
        // Countdown time interval
        private const val ONE_SECOND = 1000L
        // Total time
        private const val COUNTDOWN_TIME = 60000L
    }

    private val timer: CountDownTimer
    // Countdown time
    private val _currentTime = MutableLiveData<Long>()
    val currentTime: LiveData<Long>
        get() = _currentTime
    private var _loginInfo = MutableLiveData<LoginLoginInfo>()
    val loginInfo: LiveData<LoginLoginInfo>
        get() = _loginInfo
    //是否禁用登录按钮
    private var _forbidden = MutableLiveData<Boolean>()
    val forbidden: LiveData<Boolean>
        get() = _forbidden
    //是否禁用发送验证码按钮
    private var _forbiddenCode = MutableLiveData<Boolean>()
    val forbiddenCode: LiveData<Boolean>
        get() = _forbiddenCode
    //是否是密码登录
    private var _isPwdLogin = MutableLiveData<Boolean>()
    val isPwdLogin: LiveData<Boolean>
        get() = _isPwdLogin

    private var phone = ""
    private var code = ""
    var phoneWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            phone = s.toString()
            judge()
            _forbiddenCode.value = phone.isEmpty() || phone.length != 11
        }

        override fun afterTextChanged(s: Editable) {}
    }
    var codeWatcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            code = s.toString()
            judge()
        }

        override fun afterTextChanged(s: Editable) {}
    }

    init {
        timer = object : CountDownTimer(COUNTDOWN_TIME, ONE_SECOND) {

            override fun onTick(millisUntilFinished: Long) {
                _currentTime.value = millisUntilFinished / ONE_SECOND
            }

            override fun onFinish() {
                _currentTime.value = DONE
            }
        }
        _isPwdLogin.value = true
        _forbidden.value = true
        _forbiddenCode.value = true
    }

    fun judge() {
        if (phone.isEmpty()) {
            _forbidden.value = true
            return
        }
        if (code.isEmpty()) {
            _forbidden.value = true
            return
        }
        if (phone.length != 11) {
            _forbidden.value = true
            return
        }
        _forbidden.value = false
    }

    fun pwdLogin() {
        _isPwdLogin.value = true
    }

    fun codeLogin() {
        _isPwdLogin.value = false
        _forbiddenCode.value = phone.isEmpty() || phone.length != 11
    }

    /**
     * 登陆
     */
    fun login() {
        if (!_isPwdLogin.value!!) {
            if (code.length != 4) {
                ToastUtil.showShort("验证码格式不正确")
                return
            }
        }

        val map = getNewMap()
        putPhone(map, phone)
        if (_isPwdLogin.value!!) {
            putPwd(map, code)
        } else {
            putCode(map, code)
        }
        putSign(map)
        viewModelScope.launch {
            val loginAsync = if (_isPwdLogin.value!!) {
                BusinessApi.retrofitService.pwdLoginAsync(map)
            } else {
                BusinessApi.retrofitService.loginAsync(map)
            }
            try {
                val info = loginAsync.await()
                _loginInfo.value = info
                if (info.code == 200) {
                    val data = info.data
                    putUid(data.getId().toString() + "")
                    putName(data.getName())
                    putPhone(data.getPhone())
                    putLevel(data.getPname())
                    putDepartment(data.getDname())
                    putPersonalPermission(data.getType())
                    putWhetherCanCreateMeeting(data.getFlag())
                    putWhetherIsStaff(data.is_staff)
                }
            } catch (e: Exception) {
                Logger.e(e.toString())
            }
        }
    }

    fun sendSMS() {
        val map = getNewMap()
        putTELPhone(map, phone)
        putSign(map)
        viewModelScope.launch {
            val sendSMSAsync = BusinessApi.retrofitService.sendSMSAsync(map)
            try {
                val info = sendSMSAsync.await()
                if (info.code == 1) {
                    ToastUtil.showShort("发送验证码成功")
                    timer.start()
                }
            } catch (e: Exception) {
                Logger.e(e.toString())
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        // Cancel the timer
        timer.cancel()
    }
}